#!/bin/bash

# This script is loosly based on a script with same purpose provided
# by RIOT-OS (https://github.com/RIOT-OS/RIOT)

BIN_PATH=${2}
JLINK_EXE=${JLINK_EXE:-/usr/bin/JLinkExe}
JLINK_GDBSERVER=${JLINK_GDBSERVER:-/usr/bin/JLinkGDBServer}
JLINK_LOAD_ADDR=${JLINK_LOAD_ADDR:-0x08000000}
EXEC_DEVICE=${EXEC_DEVICE:-CORTEX-M3}
GdbCmd=${ROOT_PATH}/debug/.gdb_cmd

do_flash() {
	#--------------------------------------------------
	#	program binfile, usage: ./program firmware.bin/hex
	#	chip:Atmel
	#	start addr:0x08000000
	#--------------------------------------------------

	local cmdfile="./.tmp.jlink"
	local start_addr=${JLINK_LOAD_ADDR}

	if [ "${BIN_NAME}" == 'n' ]; then
		return 0
	fi

	if [ "${BIN_PATH}" == "" ]; then
		echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} Binary file not specified\n"
		exit 1
	elif [ ! -f ${BIN_PATH} ]; then
		echo -e "\033[31m[ERROR]\033[0m ${BASH_SOURCE}:${LINENO} Usage: file '${BIN_PATH}' not exit, Please select correct file\n"
		exit 1
	fi

	local filename=$(basename "${BIN_PATH}")

	if [ -f $cmdfile ]; then
		rm -f $cmdfile
	fi
	if [ ! -f $cmdfile ]; then
		touch $cmdfile

		echo r > $cmdfile
		echo h >> $cmdfile
		if [ "${filename##*.}" = "bin" ]; then	
			echo loadfile ${BIN_PATH} $start_addr >> $cmdfile
		else
			echo loadfile ${BIN_PATH} >> $cmdfile
		fi
		echo mem32 ${start_addr} 10 >> $cmdfile
		echo r >> $cmdfile
		echo qc >> $cmdfile
	fi

	echo -e "\n\033[35m--== Loading file ==--\033[0m\n"
	${JLINK_EXE} -if SWD -speed 4000 -device ${EXEC_DEVICE} -CommanderScript $cmdfile

	if [ -f $cmdfile ]; then
		rm -f $cmdfile
	fi
}


cleanup() {
	echo exit!
}

do_debugserver() {

	trap "cleanup" EXIT
	
	rm -f ${GdbCmd}
	echo 'Waiting for debugcmd...'
	while :; do
		sleep 0.1
		if [ -f ${GdbCmd} ]; then
			param=(`sed -n '1p' ${GdbCmd}`)
			rm -f ${GdbCmd}
			sh -c "${param[0]}  -if swd -speed 4000 -device ${param[1]} -noir -LocalhostOnly -autoconnect 1"
			clear
			sleep 0.1
			echo 'Waiting for debugcmd...'
		fi
	done
}

do_debugserver_run() {

	trap "cleanup" EXIT
	sh -c "${JLINK_GDBSERVER}  -if swd -speed 4000 -device ${EXEC_DEVICE} -noir -LocalhostOnly -autoconnect 1"
}

do_debugcmd() {
	echo ${JLINK_GDBSERVER} ${EXEC_DEVICE} > ${GdbCmd}
}

CMD="$1"
shift

case "${CMD}" in
  flash)
	echo "Flashing Target Device"
	do_flash "$@"
	;;
  debugserver)
	do_debugserver "$@"
	;;
  debugserver_run)
	do_debugserver_run "$@"
	;;
  debugcmd)
	do_debugcmd "$@"
	;;
esac
